""" handlers.py

This module provides the base API handler class for the AppEngine
InFlightXt application.

   Copyright 2011 Bravo369.org

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

author = mmeade@google.com
"""


class Handler(object):
  """Api handler base class."""

  def __init__(self, request, response, query={}):
    """Constructor.

    Args:
      request: The request instance received by the request handler class.
      response: The response instance reveived by the request handler class.
      query: The query dictionary (optional).
    """
    self.request = request
    self.response = response
    self.query = query

  @classmethod
  def filter(cls, all, filters={}, max_results=500, order=None):
    """Convenience implementation of the database filter method.

    Args:
      all: The all() response object of a database model.
      filters: A dictionary of "keyName condition:keyValue" (optional).
      max_results: The max number of results to return (optional).
      order: The keyName to filter on (optional).

    Returns:
      The result of the filter operation.
    """
    for name, value in filters.items():
      all.filter(name, value)
    if order:
      all.order(order)
    return all.fetch(max_results)

  @classmethod
  def get(cls, handlerName, default):
    """Return the handler method, or the indicated default.

    args:
      handlerName: The name of the handler method.
      default: The default value to return if the handler is not found.

    Returns:
      Either the handler method or the indicated default.
    """
    return getattr(cls, handlerName, default)
